/**
 * 数据血缘页面 - 简化版
 * 只包含两个核心功能：测试连接和解析数据库
 */

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Row,
  Col,
  Card,
  Button,
  Space,
  Descriptions,
  Typography,
  Alert,
  Spin,
  Progress,
  List,
  Tag,
  Statistic,
  Divider,
  theme,
} from 'antd';
import { useTheme } from '../contexts/ThemeContext';
import { startAnalysisProgress, updateAnalysisProgress, completeAnalysisProgress } from '../utils/globalProgressManager';
import { messageSuccess, messageError, messageInfo, messageWarning } from '../utils/notification';
import {
  DatabaseOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  ClockCircleOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { LineageService } from '../services/lineageService';
import HierarchicalLineageGraph from '../components/HierarchicalLineageGraph';
import PerformanceMonitor from '../components/PerformanceMonitor';
import { validateDataLineagePerformance } from '../utils/performanceValidation';

import type { LineageGraphData } from '../services/lineageService';

const { Title, Paragraph } = Typography;

// 数据库连接测试结果接口
interface DatabaseConnectionTest {
  success: boolean;
  message: string;
  connection_time: number;
  database_info?: {
    host: string;
    database: string;
    total_tasks: number;
    enabled_tasks: number;
    tasks_with_sql: number;
  };
  error_details?: string;
}

// 批量分析结果接口
interface BatchAnalysisResponse {
  total_tasks: number;
  success_count: number;
  failed_count: number;
  processing_time: number;
  results: Array<{
    task_id: number;
    task_name: string;
    success: boolean;
    node_count?: number;
    edge_count?: number;
    error?: string;
  }>;
}

// 任务血缘结果接口
interface TaskLineageResult {
  task_id: number;
  task_name: string;
  nodes: Array<{
    id: string;
    label: string;
    type: string;
    task_id?: number;
    task_name?: string;
  }>;
  edges: Array<{
    source: string;
    target: string;
    type: string;
    task_id?: number;
    task_name?: string;
  }>;
  node_count: number;
  edge_count: number;
  sql_length?: number;
}

// 任务级节点接口
interface TaskLevelNode {
  id: string;
  label: string;
  type: 'task';
  task_id: number;
  task_name: string;
  node_count: number;
  edge_count: number;
  source_tables: string[];
  target_tables: string[];
  internal_nodes: any[];
  internal_edges: any[];
}

// 任务级边接口
interface TaskLevelEdge {
  source: string;
  target: string;
  type: 'task_dependency';
  common_tables: string[];
  source_task_name: string;
  target_task_name: string;
}

// 数据库解析结果接口
interface DatabaseParseResult {
  total_tasks: number;
  task_info?: Array<{
    id: number;
    name: string;
    sql_length: number;
  }>;
  task_lineage_results?: TaskLineageResult[];
  task_level_nodes?: TaskLevelNode[];
  task_level_edges?: TaskLevelEdge[];
  nodes: Array<{
    id: string;
    label: string;
    type: string;
  }>;
  edges: Array<{
    source: string;
    target: string;
    type: string;
    sql_index?: number;
  }>;
  connectors: string[];
  statistics: {
    total_nodes: number;
    total_edges: number;
    total_connectors: number;
    task_level_nodes?: number;
    task_level_edges?: number;
    sql_statements_processed?: number;
    tasks_processed?: number;
    processing_time: number;
  };
}

const DataLineageComponent: React.FC = () => {
  const { token } = theme.useToken();
  const { currentTheme } = useTheme();
  // 移除进度管理hooks，使用全局进度管理器

  // 状态管理
  const [connectionTesting, setConnectionTesting] = useState(false);
  const [connectionResult, setConnectionResult] = useState<DatabaseConnectionTest | null>(null);
  const [analyzing, setAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState<BatchAnalysisResponse | null>(null);
  const [parseResult, setParseResult] = useState<DatabaseParseResult | null>(null);
  const [loading, setLoading] = useState(true); // 页面初始加载状态
  const [dataSource, setDataSource] = useState<'cache' | 'fresh' | null>(null); // 数据来源

  // 解析状态管理
  const [parseStatus, setParseStatus] = useState<'idle' | 'running' | 'completed' | 'failed'>('idle');

  // 防止重复请求的ref
  const isLoadingCacheRef = useRef(false);
  const isTestingConnectionRef = useRef(false);
  const isAnalyzingRef = useRef(false);
  const cacheLoadedRef = useRef(false);

  // 使用useRef存储不需要触发渲染的数据
  const analysisIdRef = useRef<string | null>(null);

  // 使用useMemo缓存血缘图数据，只有parseResult真正变化时才重新创建
  const lineageGraphData = useMemo(() => {
    if (!parseResult) return null;

    return {
      task_level_nodes: parseResult.task_level_nodes,
      task_level_edges: parseResult.task_level_edges,
      task_lineage_results: parseResult.task_lineage_results,
      nodes: parseResult.nodes,
      edges: parseResult.edges,
      connectors: parseResult.connectors
    };
  }, [parseResult]);


  // 加载缓存数据的函数 - 使用useCallback和ref防止重复请求
  const loadCachedData = useCallback(async () => {
    if (isLoadingCacheRef.current || cacheLoadedRef.current) {

      return;
    }

    isLoadingCacheRef.current = true;
    setLoading(true);

    try {

      const response = await LineageService.getCachedLineageData();

      if (response.success && response.data) {
        setParseResult(response.data);
        setDataSource('cache');
        cacheLoadedRef.current = true;
        messageSuccess(`✅ 已加载缓存的血缘数据: ${response.data.statistics?.tasks_processed || 0} 个任务`);
      } else {
        messageInfo('💡 暂无缓存的血缘数据，请点击"解析数据库"生成血缘图');
      }
    } catch (error) {
      console.error('加载缓存数据失败:', error);
      messageWarning('⚠️ 加载缓存数据失败，请点击"解析数据库"重新生成');
    } finally {
      isLoadingCacheRef.current = false;
      setLoading(false);
    }
  }, []);

  // 页面加载时获取缓存的血缘数据 - 只执行一次
  useEffect(() => {
    loadCachedData();
  }, [loadCachedData]);

  // 性能验证 - 仅在开发环境下运行
  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      // 延迟执行性能验证，确保组件完全加载
      setTimeout(() => {
        validateDataLineagePerformance().then(metrics => {
          if (metrics.passed) {
            console.log('🎉 DataLineage组件性能优化成功！');
          } else {
            console.warn('⚠️ DataLineage组件仍需进一步优化');
          }
        });
      }, 2000);
    }
  }, []);





  // 刷新缓存数据 - 使用useCallback和ref防止重复请求
  const refreshCachedData = useCallback(async () => {
    if (isLoadingCacheRef.current) {

      return;
    }

    isLoadingCacheRef.current = true;
    setLoading(true);

    try {
      const response = await LineageService.getCachedLineageData();

      if (response.success && response.data) {
        setParseResult(response.data);
        setDataSource('cache');
        messageSuccess('✅ 缓存数据已刷新');
      } else {
        messageInfo('💡 暂无缓存的血缘数据');
      }
    } catch (error) {
      console.error('刷新缓存数据失败:', error);
      messageError('❌ 刷新缓存数据失败');
    } finally {
      isLoadingCacheRef.current = false;
      setLoading(false);
    }
  }, []);

  // 测试数据库连接 - 使用useCallback和ref防止重复请求
  const testDatabaseConnection = useCallback(async () => {
    if (isTestingConnectionRef.current) {
      return;
    }

    isTestingConnectionRef.current = true;
    setConnectionTesting(true);
    setConnectionResult(null);

    try {
      const response = await fetch('http://localhost:8000/api/v1/lineage/test-connection');
      const result = await response.json();

      if (result.success) {
        setConnectionResult(result.data);
        messageSuccess('✅ 数据库连接测试成功！');
      } else {
        setConnectionResult(result.data);
        messageError('❌ 数据库连接测试失败！');
      }
    } catch (error) {
      console.error('连接测试失败:', error);
      messageError('❌ 连接测试失败，请检查后端服务');
      setConnectionResult({
        success: false,
        message: '无法连接到后端服务',
        connection_time: 0,
        error_details: String(error)
      });
    } finally {
      isTestingConnectionRef.current = false;
      setConnectionTesting(false);
    }
  }, []);

  // 解析数据库生成血缘图 - 集成Dynamic Island状态显示
  const analyzeDatabase = useCallback(async () => {
    if (!connectionResult?.success) {
      messageWarning('⚠️ 请先测试数据库连接！');
      return;
    }

    if (isAnalyzingRef.current) {
      return;
    }

    isAnalyzingRef.current = true;
    setAnalyzing(true);
    setParseResult(null);
    setParseStatus('running');

    // 启动Dynamic Island通知
    const notificationId = startAnalysisProgress('Dinky数据库');
    analysisIdRef.current = notificationId;
    const startTime = Date.now();

    let progressInterval: NodeJS.Timeout;
    let currentProgress = 0; // 使用局部变量而不是状态

    try {
      // 模拟进度更新，同时更新Dynamic Island
      progressInterval = setInterval(() => {
        // 更新局部进度变量，不触发组件重新渲染
        currentProgress = currentProgress >= 90 ? currentProgress : currentProgress + Math.random() * 8 + 2;
        const newProgress = currentProgress;

          // 更新Dynamic Island进度 - 提供更详细的阶段信息和统计数据
          let stage = '初始化解析引擎';
          let currentTable = '';
          let processedTables = 0;
          let totalTables = 0;
          let estimatedTime = 0;

          if (newProgress <= 15) {
            stage = '初始化解析引擎';
            currentTable = '连接数据库';
            processedTables = 0;
            totalTables = 25;
            estimatedTime = 45;
          } else if (newProgress <= 35) {
            stage = '扫描任务表';
            currentTable = 'dlink_task';
            processedTables = Math.floor((newProgress - 15) / 20 * 8);
            totalTables = 25;
            estimatedTime = 35;
          } else if (newProgress <= 55) {
            stage = '解析SQL语句';
            currentTable = 'FlinkSQL任务';
            processedTables = 8 + Math.floor((newProgress - 35) / 20 * 10);
            totalTables = 25;
            estimatedTime = 25;
          } else if (newProgress <= 75) {
            stage = '构建血缘关系';
            currentTable = '数据流图';
            processedTables = 18 + Math.floor((newProgress - 55) / 20 * 5);
            totalTables = 25;
            estimatedTime = 15;
          } else if (newProgress <= 90) {
            stage = '生成结果';
            currentTable = '血缘关系图';
            processedTables = 23 + Math.floor((newProgress - 75) / 15 * 2);
            totalTables = 25;
            estimatedTime = 5;
          } else {
            stage = '完成解析';
            currentTable = '保存到数据库';
            processedTables = 25;
            totalTables = 25;
            estimatedTime = 0;
          }

          updateAnalysisProgress(
            notificationId,
            Math.round(newProgress),
            stage,
            currentTable,
            {
              processedTables,
              totalTables,
              estimatedTimeRemaining: estimatedTime,
              currentOperation: stage
            }
          );

          if (newProgress >= 90) {
            clearInterval(progressInterval);
          }
      }, 800); // 稍微放慢进度更新，让用户能看清楚

      const response = await LineageService.parseDatabaseLineage();

      clearInterval(progressInterval);
      // 不再需要设置进度状态

      if (response.success && response.data) {
        setParseResult(response.data);
        setDataSource('fresh'); // 标记为新解析的数据
        cacheLoadedRef.current = true; // 标记缓存已更新
        setParseStatus('completed');

        const nodeCount = response.data.statistics?.total_nodes || response.data.nodes?.length || 0;
        const duration = Date.now() - startTime;

        // 完成Dynamic Island通知 - 提供详细的统计信息
        const summaryText = `解析完成：${response.data.total_tasks || 25}个任务，${nodeCount}个节点`;
        completeAnalysisProgress(notificationId, true, summaryText, {
          tables: response.data.total_tasks || processedTables || 25,
          relations: nodeCount,
          duration
        });

        messageSuccess(`✅ FlinkSQL解析完成！解析了 ${response.data.total_tasks || 25} 个任务，生成 ${nodeCount} 个节点，并已保存到数据库`);
      } else {
        setParseStatus('failed');
        // 失败的Dynamic Island通知 - 提供具体错误信息
        const errorMsg = response.message || '数据库解析失败';
        completeAnalysisProgress(notificationId, false, errorMsg);
        messageError(`❌ ${errorMsg}`);
      }
    } catch (error) {
      console.error('数据库解析失败:', error);
      setParseStatus('failed');

      // 失败的Dynamic Island通知 - 区分网络错误和服务错误
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      const isNetworkError = errorMessage.includes('fetch') || errorMessage.includes('network');
      const displayMessage = isNetworkError ? '无法连接到后端服务' : '数据库解析过程中发生错误';

      completeAnalysisProgress(notificationId, false, displayMessage);
      messageError(`❌ ${displayMessage}`);

      if (progressInterval!) {
        clearInterval(progressInterval);
      }
    } finally {
      isAnalyzingRef.current = false;
      setAnalyzing(false);
      // 不再需要重置进度状态
    }
  }, [connectionResult?.success]); // 移除进度管理函数依赖，因为它们是全局函数









  return (
    <PerformanceMonitor componentName="DataLineage">
      <div style={{ padding: '24px' }}>
      <Title level={2}>数据血缘分析系统</Title>
      <Paragraph type="secondary">
        通过解析数据库中的FlinkSQL语句，自动生成数据血缘关系图，帮助您理解数据流向和依赖关系。
      </Paragraph>



      <Row gutter={[24, 24]}>
        {/* 操作面板 */}
        <Col span={24}>
          <Card title="操作面板" size="small">
            <Row gutter={[16, 16]} wrap>
              <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                <Button
                  type="primary"
                  icon={<DatabaseOutlined />}
                  loading={connectionTesting}
                  onClick={testDatabaseConnection}
                  size="middle"
                  block
                >
                  {connectionTesting ? '测试中...' : '测试连接'}
                </Button>
              </Col>

              <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                <Button
                  type="primary"
                  icon={<PlayCircleOutlined />}
                  loading={analyzing}
                  onClick={analyzeDatabase}
                  disabled={!connectionResult?.success}
                  size="middle"
                  block
                  style={{ backgroundColor: token.colorSuccess, borderColor: token.colorSuccess }}
                >
                  {analyzing ? '解析中...' : '解析数据库'}
                </Button>
              </Col>

              <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                <Button
                  icon={<ReloadOutlined />}
                  loading={loading}
                  onClick={refreshCachedData}
                  size="middle"
                  block
                >
                  {loading ? '刷新中...' : '刷新缓存'}
                </Button>
              </Col>

              {dataSource && (
                <Col xs={24} sm={12} md={8} lg={6} xl={9} style={{ display: 'flex', alignItems: 'center' }}>
                  <Tag
                    color={dataSource === 'fresh' ? 'green' : 'blue'}
                    style={{
                      fontSize: '14px',
                      padding: '4px 12px',
                      margin: 0,
                      borderRadius: '6px'
                    }}
                  >
                    {dataSource === 'fresh' ? '✨ 最新解析数据' : '📦 缓存数据'}
                  </Tag>
                </Col>
              )}
            </Row>
            
            {/* 进度显示已移至 Dynamic Island，不再需要这里的进度条 */}
          </Card>
        </Col>

        {/* 连接测试结果 */}
        {connectionResult && (
          <Col span={12}>
            <Card 
              title={
                <Space>
                  {connectionResult.success ? (
                    <CheckCircleOutlined style={{ color: '#52c41a' }} />
                  ) : (
                    <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
                  )}
                  数据库连接状态
                </Space>
              }
              size="small"
            >
              <Alert
                message={connectionResult.message}
                type={connectionResult.success ? 'success' : 'error'}
                showIcon
                style={{ marginBottom: 16 }}
              />
              
              <Descriptions column={1} size="small">
                <Descriptions.Item label="连接时间">
                  <Space>
                    <ClockCircleOutlined />
                    {(connectionResult.connection_time || 0).toFixed(3)}s
                  </Space>
                </Descriptions.Item>
                
                {connectionResult.database_info && (
                  <>
                    <Descriptions.Item label="数据库">
                      {connectionResult.database_info.database}@{connectionResult.database_info.host}
                    </Descriptions.Item>
                    <Descriptions.Item label="任务统计">
                      <Space>
                        <Tag color="blue">总数: {connectionResult.database_info.total_tasks}</Tag>
                        <Tag color="green">启用: {connectionResult.database_info.enabled_tasks}</Tag>
                        <Tag color="orange">有SQL: {connectionResult.database_info.tasks_with_sql}</Tag>
                      </Space>
                    </Descriptions.Item>
                  </>
                )}
                
                {connectionResult.error_details && (
                  <Descriptions.Item label="错误详情">
                    <Typography.Text type="danger" code>
                      {connectionResult.error_details}
                    </Typography.Text>
                  </Descriptions.Item>
                )}
              </Descriptions>
            </Card>
          </Col>
        )}

        {/* 解析结果统计 */}
        {parseResult && (
          <Col span={12}>
            <Card title="FlinkSQL解析结果" size="small">
              <Row gutter={16}>
                <Col span={4}>
                  <Statistic
                    title="任务数"
                    value={parseResult.task_level_nodes?.length || parseResult.total_tasks || 0}
                    prefix={<DatabaseOutlined />}
                  />
                </Col>
                <Col span={4}>
                  <Statistic
                    title="任务依赖"
                    value={parseResult.task_level_edges?.length || parseResult.statistics?.task_level_edges || 0}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Col>
                <Col span={4}>
                  <Statistic
                    title="表节点"
                    value={parseResult.nodes?.length || parseResult.statistics?.total_nodes || 0}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Col>
                <Col span={4}>
                  <Statistic
                    title="表连接"
                    value={parseResult.edges?.length || parseResult.statistics?.total_edges || 0}
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Col>
                <Col span={4}>
                  <Statistic
                    title="连接器"
                    value={parseResult.connectors?.length || parseResult.statistics?.total_connectors || 0}
                    valueStyle={{ color: '#faad14' }}
                  />
                </Col>
                <Col span={4}>
                  <Statistic
                    title="处理时间"
                    value={(parseResult.statistics.processing_time || 0).toFixed(1)}
                    suffix="s"
                    valueStyle={{ color: '#13c2c2' }}
                  />
                </Col>
              </Row>

              <Divider />

              <Descriptions column={2} size="small">
                <Descriptions.Item label="处理时间">
                  {(parseResult.statistics.processing_time || 0).toFixed(2)}s
                </Descriptions.Item>
                <Descriptions.Item label="处理任务数">
                  {parseResult.statistics.tasks_processed || parseResult.statistics.sql_statements_processed || 0}
                </Descriptions.Item>
              </Descriptions>

              {/* 连接器类型统计 */}
              {parseResult.connectors.length > 0 && (
                <>
                  <Divider />
                  <div>
                    <Typography.Text strong>连接器类型统计：</Typography.Text>
                    <div style={{ marginTop: 8 }}>
                      <Space wrap>
                        <Tag color="blue">总数: {parseResult.connectors.length}</Tag>
                        <Tag color="green">
                          Kafka: {parseResult.connectors.filter(c => c.toLowerCase().includes('kafka')).length}
                        </Tag>
                        <Tag color="orange">
                          Doris: {parseResult.connectors.filter(c => c.toLowerCase().includes('doris')).length}
                        </Tag>
                        <Tag color="purple">
                          HBase: {parseResult.connectors.filter(c => c.toLowerCase().includes('hbase')).length}
                        </Tag>
                        <Tag color="cyan">
                          其他: {parseResult.connectors.filter(c =>
                            !c.toLowerCase().includes('kafka') &&
                            !c.toLowerCase().includes('doris') &&
                            !c.toLowerCase().includes('hbase')
                          ).length}
                        </Tag>
                      </Space>

                      {/* 可展开的详细列表 */}
                      <div style={{ marginTop: 8 }}>
                        <Typography.Link
                          onClick={() => {
                            const detailDiv = document.getElementById('connector-details');
                            if (detailDiv) {
                              detailDiv.style.display = detailDiv.style.display === 'none' ? 'block' : 'none';
                            }
                          }}
                        >
                          {parseResult.connectors.length > 5 ? '查看详细列表 ▼' : ''}
                        </Typography.Link>
                        <div id="connector-details" style={{ display: 'none', marginTop: 8, maxHeight: 200, overflow: 'auto' }}>
                          {parseResult.connectors.map((connector, index) => (
                            <Tag key={index} color="blue" style={{ marginBottom: 4, fontSize: '11px' }}>
                              {connector}
                            </Tag>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                </>
              )}
            </Card>
          </Col>
        )}

        {/* 任务详细信息 */}
        {parseResult && parseResult.task_info && parseResult.task_info.length > 0 && (
          <Col span={24}>
            <Card title="任务详细信息" size="small">
              <List
                size="small"
                dataSource={parseResult.task_info}
                pagination={{
                  pageSize: 10,
                  showSizeChanger: false,
                  showQuickJumper: true,
                }}
                renderItem={(item) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<DatabaseOutlined style={{ color: '#1890ff' }} />}
                      title={
                        <Space>
                          <span>{item.name}</span>
                          <Tag color="blue">ID: {item.id}</Tag>
                        </Space>
                      }
                      description={
                        <Space>
                          <span>SQL长度: {item.sql_length} 字符</span>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        )}

        {/* 数据血缘图 - 使用层次化血缘图组件 */}
        <Col span={24}>
          {loading && !parseResult ? (
            <Card>
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" />
                <div style={{ marginTop: 16 }}>正在加载血缘数据...</div>
              </div>
            </Card>
          ) : (
            <HierarchicalLineageGraph
              data={lineageGraphData}
              loading={analyzing}
            />
          )}
        </Col>
      </Row>
      </div>
    </PerformanceMonitor>
  );
};

// 使用React.memo优化整个DataLineage组件
const DataLineage = React.memo(DataLineageComponent);

export default DataLineage;
